package fr.emse.tsc;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LenAccess extends Activity {
	static final int DIALOG_DISCONNECT = 0;
	static final int DIALOG_ERROR = 1;
	static final int DIALOG_QUIT = 2;

	private String addressIP = null;
	private int port = 0;
	private String lname = null;
	private Connexion conn = new Connexion();
	private String errorMessage = null;
	private EditText history = null;
	private EditText texte = null;
	private Button bSend = null;
	
	public void showToast() {
    	Toast toast = Toast.makeText(this, "Connect " + lname + " to " + addressIP, Toast.LENGTH_SHORT);
    	toast.setGravity(Gravity.CENTER, 0, 0);
    	toast.show();
	}
	
    private OnClickListener mLenListener = new OnClickListener() {
        public void onClick(View v) {
        	if (LenAccess.this.texte.length() > 0) {
        		LenAccess.this.history.append(lname + ": " + LenAccess.this.texte.getText().toString() + "\n");
        		String reponse;
				try {
					reponse = conn.sendMessage(LenAccess.this.texte.getText().toString());
					LenAccess.this.history.append("Server:" + reponse + "\n");
				}
				catch (IOException e) {
					errorMessage = e.toString();
					showDialog(DIALOG_ERROR);
				}
        	}
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tsc_len);
        history = (EditText) findViewById(R.id.messageHistory);
        texte = (EditText) findViewById(R.id.message);
        bSend = (Button) findViewById(R.id.bMessage);
        bSend.setOnClickListener(mLenListener);
        addressIP = Config.getLServer(this);
        port = Integer.parseInt(Config.getLPort(this));
        lname = Config.getLName(this);
        Log.i("LENACCESS", "On Create: " + addressIP);
    	showToast();
    	try {
			conn.connect(addressIP, port, lname);
		} catch (IOException e) {
			errorMessage = e.toString();
			showDialog(DIALOG_ERROR);
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog alert = null;
		switch (id) {
		case DIALOG_DISCONNECT: 
			builder.setMessage("Are you sure you want to disconnect?")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					try {
						conn.disconnect();
					} catch (IOException e) {
						errorMessage = e.toString();
						showDialog(DIALOG_QUIT);
					}
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			break;
		case DIALOG_QUIT: 
			builder.setMessage("Are you sure you want to quit?")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					try {
						conn.disconnect();
					} catch (IOException e) {
						errorMessage = e.toString();
						showDialog(DIALOG_QUIT);
					}
					finish();
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			break;
		case DIALOG_ERROR:
			builder.setMessage("Error: ")
			.setCancelable(false)
			.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			})
			.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					try {
						conn.disconnect();
					} catch (IOException e) {
						errorMessage = e.toString();
						showDialog(DIALOG_QUIT);
					}
					finish();
				}
			});
			break;
		}
		alert = builder.create();
		return alert;			
	}
	
    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case DIALOG_DISCONNECT:
            	if (conn.isConnected()) {
            		((AlertDialog) dialog).setMessage("You are connected: disconnect?");
            	}
            	break;
            case DIALOG_QUIT:
            	break;
           case DIALOG_ERROR:
                ((AlertDialog) dialog).setMessage(errorMessage);
                break;
        }
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }

	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.mConnect :
        	if (conn.isConnected()) {
        		showDialog(DIALOG_DISCONNECT);
        	}
        	try {
                addressIP = Config.getLServer(this);
                port = Integer.parseInt(Config.getLPort(this));
        		lname = Config.getLName(this);
            	showToast();
				conn.connect(addressIP, port, lname);
			} catch (IOException e) {
				errorMessage = e.toString();
				showDialog(DIALOG_QUIT);
			}
            return true;
        case R.id.mDisconnect :
            showDialog(DIALOG_DISCONNECT);
            return true;
        case R.id.mQuit :
        	showDialog(DIALOG_QUIT);
        	return true;
        }
        return false;
    }
    
}
